package com.example.administrator.testc.WebVideo;/**
 * Created by maze on 2016/6/30.
 */

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout.LayoutParams;

import com.example.administrator.testc.R;

import java.io.ByteArrayOutputStream;
import java.lang.reflect.Field;


/**
 * >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>类描述
 * >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>属性描述
 * >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>方法描述
 */
public class TestMain extends Activity{

    // webView的容器
    private LinearLayout webViewLinear;
    private WebView webview;// 显示网页内容
    WebSettings settings = null;
    private Button commentEditText;// 评论文本编辑框
    // 全屏播放
    private FrameLayout videoview;// 全屏时视频加载view
    private View xCustomView;
    private xWebChromeClient xwebchromeclient;
    private WebChromeClient.CustomViewCallback xCustomViewCallback;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view_detail);
        webViewLinear = (LinearLayout) this.findViewById(R.id.webview_linear);

        webview = new WebView(this);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        webview.setLayoutParams(params);

        webViewLinear.addView(webview);
        // 全屏播放界面
        videoview = (FrameLayout) findViewById(R.id.video_view);
        // webview的设置
        settings = webview.getSettings();

        /**
         * setAllowFileAccess 启用或禁止WebView访问文件数据 setBlockNetworkImage 是否显示网络图像
         * setBuiltInZoomControls 设置是否支持缩放 setCacheMode 设置缓冲的模式
         * setDefaultFontSize 设置默认的字体大小 setDefaultTextEncodingName 设置在解码时使用的默认编码
         * setFixedFontFamily 设置固定使用的字体 setJavaSciptEnabled 设置是否支持Javascript
         * setLayoutAlgorithm 设置布局方式 setLightTouchEnabled 设置用鼠标激活被选项
         * setSupportZoom 设置是否支持变焦
         * */
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);// 排版适应屏幕
        settings.setUseWideViewPort(true);// 可任意比例缩放
        settings.setLoadWithOverviewMode(true);// setUseWideViewPort方法设置webview推荐使用的窗口。setLoadWithOverviewMode方法是设置webview加载的页面的模式。
        settings.setSavePassword(true);
        settings.setSaveFormData(true);// 保存表单数据
        settings.setJavaScriptEnabled(true);
        settings.setGeolocationEnabled(true);// 启用地理定位
        settings.setGeolocationDatabasePath("/data/data/org.itri.html5webview/databases/");// 设置定位的数据库路径
        settings.setDomStorageEnabled(true);

        settings.setPluginState(PluginState.ON);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setAllowFileAccess(true);
        settings.setDefaultTextEncodingName("UTF-8");
        settings.setAppCacheEnabled(true);
        settings.setRenderPriority(RenderPriority.HIGH);// 渲染级别
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        xwebchromeclient = new xWebChromeClient();
        webview.setWebChromeClient(xwebchromeclient);
        webview.setWebViewClient(new DIYWebViewClient());
        webview.loadUrl("http://m.xincheping.com/video/24084.html");
    }

    public void setConfigCallback(WindowManager windowManager) {
        try {
            Field field = WebView.class.getDeclaredField("mWebViewCore");
            field = field.getType().getDeclaredField("mBrowserFrame");
            field = field.getType().getDeclaredField("sConfigCallback");
            field.setAccessible(true);
            Object configCallback = field.get(null);

            if (null == configCallback) {
                return;
            }

            field = field.getType().getDeclaredField("mWindowManager");
            field.setAccessible(true);
            field.set(configCallback, windowManager);
        } catch (Exception e) {
        }
    }

    // 页面中链接，如果希望点击链接继续在当前browser中响应，
    // 而不是新开Android的系统browser中响应该链接，必须覆盖webview的WebViewClient对象
    private class DIYWebViewClient extends WebViewClient {
        // 这个方法在用户试图点开页面上的某个链接时被调用
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return true; // 返回true表示停留在本WebView（不跳转到系统的浏览器）
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }

        public void onReceivedError(WebView view, int errorCode,
                                    String description, String failingUrl) {
        }
    }

    /**
     * 判断是否是全屏
     *
     * @return
     */
    public boolean inCustomView() {
        return (xCustomView != null);
    }

    /**
     * 全屏时按返加键执行退出全屏方法
     */
    public void hideCustomView() {
        xwebchromeclient.onHideCustomView();
    }

    /**
     * 处理Javascript的对话框、网站图标、网站标题以及网页加载进度等
     *
     * @author
     */
    public class xWebChromeClient extends WebChromeClient {
        private Bitmap xdefaltvideo;

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            System.out.println("webView   loading --------  " + newProgress);
            super.onProgressChanged(view, newProgress);
        }

        @Override
        // 播放网络视频时全屏会被调用的方法
        public void onShowCustomView(View view,
                                     WebChromeClient.CustomViewCallback callback) {
            full(true);
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            webview.setVisibility(View.GONE);
            // 如果一个视图已经存在，那么立刻终止并新建一个
            if (xCustomView != null) {
                callback.onCustomViewHidden();
                return;
            }
            videoview.addView(view);
            xCustomView = view;
            xCustomViewCallback = callback;
            videoview.setVisibility(View.VISIBLE);
        }

        @Override
        // 视频播放退出全屏会被调用的
        public void onHideCustomView() {
            full(false);
            if (xCustomView == null)// 不是全屏播放状态
                return;
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            xCustomView.setVisibility(View.GONE);
            videoview.removeView(xCustomView);
            xCustomView = null;
            videoview.setVisibility(View.GONE);
            xCustomViewCallback.onCustomViewHidden();
            webview.setVisibility(View.VISIBLE);
        }

        private void full(boolean enable) {
            if (enable) {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
                getWindow().setAttributes(lp);
                getWindow().addFlags(
                        WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
            } else {
                WindowManager.LayoutParams attr = getWindow().getAttributes();
                attr.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
                getWindow().setAttributes(attr);
                getWindow().clearFlags(
                        WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
            }
        }

        // 视频加载添加默认图标
        @Override
        public Bitmap getDefaultVideoPoster() {
            if (xdefaltvideo == null) {
                xdefaltvideo = BitmapFactory.decodeResource(getResources(),
                        R.drawable.ic_launcher);
            }
            return xdefaltvideo;
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
    }

    // 退出程序
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (inCustomView()) {
                hideCustomView();
            } else {
                try {
                    webview.getClass().getMethod("onPause")
                            .invoke(webview, (Object[]) null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // 清理缓存
                webview.loadDataWithBaseURL(null, "", "text/html", "utf-8",
                        null);
                webViewLinear.removeView(webview);
                webview.setVisibility(View.GONE);
                webview.removeAllViews();
                webview.destroy();
                this.finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        // super.onBackPressed();
        Intent i = new Intent(Intent.ACTION_MAIN);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.addCategory(Intent.CATEGORY_HOME);
        startActivity(i);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        setConfigCallback(null);
        webview.setVisibility(View.GONE);
        webViewLinear.removeView(webview);
        webview.removeAllViews();
        webview.destroy();
        System.gc();
        super.onDestroy();
    }
}
